package recursion

import org.scalatest.{FunSpec, Matchers}

class SwapNodes extends FunSpec with Matchers {

  def swapPairs(head: ListNode): ListNode = {
    if (head == null) head
    else {
      val (_, tail) = swap(head)
      head.next = null
      tail
    }
  }

  def swap(node: ListNode): (ListNode, ListNode) = {
    println(s"${node}")
    if (node.next == null) (node, node)
    else {
      val (next, last) = swap(node.next)
      next.next = node
      (node, last)
    }
  }

  describe("reverse linked list") {
    it("recursive") {
      val a1 = new ListNode(1)
      val a2 = new ListNode(2)
      val a3 = new ListNode(3)
      val a4 = new ListNode(4)
      a1.next = a2
      a2.next = a3
      a3.next = a4

      println(swapPairs(a1))
    }
  }

}